package cn.xeblog.server.forward;

import cn.xeblog.forward.codec.SharedMessageCodec;
import cn.xeblog.forward.entity.Message;
import cn.xeblog.forward.handler.ProtocolFrameDecoder;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author eleven
 * @date 2024/12/16 10:03
 * @apiNote
 */
@Slf4j
public class ForwardClientInitializer extends ChannelInitializer<NioSocketChannel> {
    @Override
    protected void initChannel(NioSocketChannel channel) throws Exception {
        LoggingHandler loggingHandler = new LoggingHandler();
        ProtocolFrameDecoder protocolFrameDecoder = new ProtocolFrameDecoder();
        channel.pipeline()
                .addLast(protocolFrameDecoder)

                .addLast(new SharedMessageCodec())
                .addLast(new IdleStateHandler(0, 10,0))
                .addLast(loggingHandler)
                .addLast(new ChannelDuplexHandler() {
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        IdleStateEvent event = (IdleStateEvent) evt;
                        if (event.state() == IdleState.WRITER_IDLE) {
                            log.info("发送心跳数据包");
                            ctx.writeAndFlush(Message.heartbeat());
                        }
                    }
                })
                .addLast(loggingHandler)
                .addLast("forwardClientHandler", new ForwardClientChannelAdapter());
        ;
    }
}
